package com.acme.entity.util;

import java.lang.reflect.Field;
import javax.persistence.Column;
import javax.persistence.EntityManager;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class EntityChangeListener implements ChangeListener {

    private EntityManager em;

    public EntityChangeListener() {
        this.em = DBManager.getEntityManager();
    }

    @Override
    public void stateChanged(ChangeEvent e) {
        Object entity = e.getSource();
        if(verifyEntity(entity)) {
            em.getTransaction().begin();
            em.persist(entity);
            em.merge(entity);
            em.getTransaction().commit();
            em.refresh(entity);
        }
    }

    private boolean verifyEntity(Object entity) {
        boolean status = true;
        Class clazz = entity.getClass();
        status &= clazz.isAnnotationPresent(Entity.class);
        for (Field f : clazz.getDeclaredFields()) {
            f.setAccessible(true);
            if( !f.isAnnotationPresent(GeneratedValue.class) ) {
                try {
                    Column c = f.getAnnotation(Column.class);
                    if(c!=null && !c.nullable()) status &= f.get(entity) != null;
                } catch (IllegalAccessException ex) {
                    ex.printStackTrace();
                }
            }
        }
        return status;
    }

}
